package com.xyzyzglxt.system.service.impl;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Objects;

import com.xyzyzglxt.common.core.domain.TreeSelect;
import com.xyzyzglxt.common.core.domain.entity.SysUser;
import com.xyzyzglxt.common.core.domain.model.LoginUser;
import com.xyzyzglxt.common.utils.DateUtils;
import com.xyzyzglxt.system.domain.SysEvent;
import com.xyzyzglxt.common.utils.FastDFSUtils;
import com.xyzyzglxt.common.utils.SecurityUtils;
import com.xyzyzglxt.system.domain.SysUserEvent;
import com.xyzyzglxt.common.core.domain.entity.SysVolunteersTime;
import com.xyzyzglxt.system.mapper.SysEventMapper;
import com.xyzyzglxt.system.mapper.SysUserEventMapper;
import com.xyzyzglxt.system.mapper.SysUserMapper;
import com.xyzyzglxt.system.mapper.SysVolunteersTimeMapper;
import com.xyzyzglxt.system.service.ISysUserEventService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;


/**
 * 报名情况Service业务层处理
 *
 * @author xyzyzglxt
 * @date 2022-01-17
 */
@Service
public class SysUserEventServiceImpl implements ISysUserEventService {
    @Autowired
    private SysUserEventMapper sysUserEventMapper;
    @Autowired
    private SysEventMapper sysEventMapper;
    @Autowired
    private SysUserMapper sysUserMapper;
    @Autowired
    private SysVolunteersTimeMapper sysVolunteersTimeMapper;


    /**
     * 通过用户id查询报名情况
     *
     * @param userId
     * @return 报名情况
     */
    @Override
    public SysUserEvent selectSysUserEventByUserId(Long userId) {
        SysUserEvent sysUserEvent = sysUserEventMapper.selectSysUserEventByUserId(userId);
        sysUserEvent.setSysUsers(sysUserMapper.selectUserVoById(sysUserEvent.getUserId()));
        sysUserEvent.setSysEvent(sysEventMapper.selectSysEventByEventId(sysUserEvent.getEventId()));
        return sysUserEvent;
    }

    /**
     * 根据userId 和 eventId查询一个
     *
     * @param userId
     * @param eventId
     * @return
     */
    @Override
    public SysUserEvent selectOneSysUserEvent(Long userId, Long eventId) {
        SysUserEvent sysUserEvent = sysUserEventMapper.selectOneSysUserEvent(userId, eventId);
        sysUserEvent.setSysUsers(sysUserMapper.selectUserVoById(sysUserEvent.getUserId()));
        sysUserEvent.setSysEvent(sysEventMapper.selectSysEventByEventId(sysUserEvent.getEventId()));
        return sysUserEvent;
    }

    /**
     * 查询报名情况列表
     *
     * @param sysUserEvent 报名情况
     * @return 报名情况
     */
    @Override
    public List<SysUserEvent> selectSysUserEventList(SysUserEvent sysUserEvent) {

        // 判断是否为自愿者姓名查询
        if(sysUserEvent.getSysUsers()!= null && sysUserEvent.getSysUsers().getNickName() != null){
            List<SysUser> sysUsers = sysUserMapper.selectUserByNickNameList(sysUserEvent.getSysUsers().getNickName());
            if(sysUsers.size() == 0){
                return new ArrayList<SysUserEvent>();
            }
            SysUser sysUser = sysUsers.get(0);
            sysUserEvent.setUserId(sysUser.getUserId());
        }
        // 判断是否含有活动类型id
        List<SysEvent> sysEvents = null;
        if(sysUserEvent.getSysEvent() != null && sysUserEvent.getSysEvent().getEventTypeId() != null){
            SysEvent sysEvent = new SysEvent();
            sysEvent.setEventTypeId(sysUserEvent.getSysEvent().getEventTypeId());
            sysEvents = sysEventMapper.selectSysEventList(sysEvent);
            if(sysEvents.size() == 0){
                return new ArrayList<SysUserEvent>();
            }
        }

        if(sysEvents != null){
            List<SysUserEvent> sysUserEvents = new ArrayList<SysUserEvent>();
            for (SysEvent sysEvent : sysEvents) {
                sysUserEvent.setEventId(sysEvent.getEventId());
                List<SysUserEvent> sysUserEventsone = sysUserEventMapper.selectSysUserEventList(sysUserEvent);
                for (SysUserEvent sysUserEventone : sysUserEventsone) {
                    sysUserEventone.setSysUsers(sysUserMapper.selectUserVoById(sysUserEventone.getUserId()));
                    sysUserEventone.setSysEvent(sysEventMapper.selectSysEventByEventId(sysUserEventone.getEventId()));
                }
                // 合并对象
                sysUserEvents.addAll(sysUserEventsone);
            }
            return sysUserEvents;
        }

        Long roleId = SecurityUtils.getLoginUser().getUser().getRoles().get(0).getRoleId();
        // 如果为自愿者
        // 自愿者只显示自己所报名的活动以及信息
        if(roleId == 2){
            sysUserEvent.setUserId(SecurityUtils.getUserId());
        }else if(roleId == 3){
            // 招募单位只能看到自己发布活动的报名情况
            if(sysUserEvent.getEventId() == null){
                return new ArrayList<SysUserEvent>();
            }
            SysEvent sysEvent = sysEventMapper.selectSysEventByEventId(sysUserEvent.getEventId());
            // 判断是否是自己发布的活动
            if(sysEvent != null && sysEvent.getEventUserId() != SecurityUtils.getUserId()){
                return new ArrayList<SysUserEvent>();
            }
        }


        List<SysUserEvent> sysUserEvents = sysUserEventMapper.selectSysUserEventList(sysUserEvent);
        for (SysUserEvent sysUserEventone : sysUserEvents) {
            sysUserEventone.setSysUsers(sysUserMapper.selectUserVoById(sysUserEventone.getUserId()));
            sysUserEventone.setSysEvent(sysEventMapper.selectSysEventByEventId(sysUserEventone.getEventId()));
        }
        return sysUserEvents;

    }

    /**
     * 报名
     *
     * @param userId
     * @param eventId
     * @return
     */
    @Override
    @Transactional
    public int reportSysUserEvent(Long eventId, Long userId) {
        SysUserEvent sysUserEvent = new SysUserEvent();
        sysUserEvent.setUserId(userId);
        sysUserEvent.setEventId(eventId);
        SysEvent sysEvent = sysEventMapper.selectSysEventByEventId(sysUserEvent.getEventId());


        //如果未审核不能报名
        if (!sysEvent.getEventCheck().equals("1")) {
            return -1;
        }
        // 活动已开始或已结束
        else if (!sysEvent.getEventStatus().equals("0")) {
            return -2;
        }
        //已报名
        else if (sysUserEventMapper.selectOneSysUserEvent(userId, eventId) != null) {
            return -3;
        }
        // 判断报名人数是否符合要求
        else if (sysEvent.getEventRdpeoples().equals(sysEvent.getEventPeoples()) || sysEvent.getEventRdpeoples() > sysEvent.getEventPeoples()) {
            return 0;
        }
        sysEvent.setEventRdpeoples(sysEvent.getEventRdpeoples() + 1);
        sysEventMapper.updateSysEvent(sysEvent);

        //设置报名信息初始值
        if (sysUserEvent.getStatusSignUp() == null || sysUserEvent.getStatusSignUp().equals("")) {
            sysUserEvent.setStatusSignUp("0");
        }
        if (sysUserEvent.getStatusSignOut() == null || sysUserEvent.getStatusSignOut().equals("")) {
            sysUserEvent.setStatusSignOut("0");
        }
        sysUserEvent.setIsCheck("0");
        return sysUserEventMapper.insertSysUserEvent(sysUserEvent);
    }

    /**
     * 上传自愿者服务时的证明图片
     *
     * @param url
     * @param eventId
     * @param userId
     * @return
     */
    @Override
    public int updateSysEventImg(String url, Long eventId, Long userId) {
        SysUserEvent sysUserEvent = sysUserEventMapper.selectOneSysUserEvent(userId, eventId);
        // 仅能上传自己的活动照片
        if(!Objects.equals(userId, SecurityUtils.getUserId())){
            return -1;
        }


        if (sysUserEvent.getImg() != null) {
            String groupName = "group1/";
            String remoteFileName = sysUserEvent.getImg().split(groupName)[1];
            groupName = groupName.replace("/", "");
            FastDFSUtils.deleteFile(groupName, remoteFileName);
        }
        sysUserEvent.setImg(url);
        return sysUserEventMapper.updateSysUserEvent(sysUserEvent);
    }


    /**
     * 根据自愿者姓名获取报名情况详细信息
     * @param name
     * @return
     */
    @Override
    public List<SysUserEvent> seletSysUserEventByName(String name,Long eventId) {
        List<SysUser> sysUsers = sysUserMapper.selectUserByNickNameList(name);
        // 没有该自愿者信息
        if(sysUsers.size() == 0){
            return new ArrayList<SysUserEvent>();
        }
        List<SysUserEvent> sysUserEvents = new ArrayList<SysUserEvent>();
        // 遍历所有符合条件的用户信息
        for (SysUser sysUser : sysUsers) {
            SysUserEvent sysUserEvent = new SysUserEvent();
            sysUserEvent.setUserId(sysUser.getUserId());
            sysUserEvent.setEventId(eventId);
            List<SysUserEvent> sysUserEventsone = sysUserEventMapper.selectSysUserEventList(sysUserEvent);
            // 合并对象
            sysUserEvents.addAll(sysUserEventsone);
        }
        for (SysUserEvent sysUserEventone : sysUserEvents) {
            sysUserEventone.setSysUsers(sysUserMapper.selectUserVoById(sysUserEventone.getUserId()));
            sysUserEventone.setSysEvent(sysEventMapper.selectSysEventByEventId(sysUserEventone.getEventId()));
        }
        return sysUserEvents;
    }

    /**
     * 新增报名情况
     *
     * @param sysUserEvent 报名情况
     * @return 结果
     */
    @Override
    public int insertSysUserEvent(SysUserEvent sysUserEvent) {
        LoginUser loginUser = SecurityUtils.getLoginUser();
        // 自愿者或招募单位不允许新增
        Long roleId = loginUser.getUser().getRoles().get(0).getRoleId();
        if (roleId!=1){
            return 0;
        }
        return sysUserEventMapper.insertSysUserEvent(sysUserEvent);
    }

    /**
     * 修改报名情况
     *
     * @param sysUserEvent 报名情况
     * @return 结果
     */
    @Override
    public int updateSysUserEvent(SysUserEvent sysUserEvent) {

        LoginUser loginUser = SecurityUtils.getLoginUser();
        // 自愿者或招募单位不允许修改
        Long roleId = loginUser.getUser().getRoles().get(0).getRoleId();
        if (roleId!=1){
            return 0;
        }
        return sysUserEventMapper.updateSysUserEvent(sysUserEvent);
    }

    /**
     * 签到
     *
     * @return
     */
    @Override
    public int SignUp(SysUserEvent sysUserEvent) {
        SysEvent sysEvent = sysEventMapper.selectSysEventByEventId(sysUserEvent.getEventId());
        SysUserEvent exist = sysUserEventMapper.selectOneSysUserEvent(sysUserEvent.getUserId(), sysUserEvent.getEventId());

        int result = checkRole(exist.getUserId(),exist.getEventId());
        if(result != 0){
            return result;
        }

        //未报名
        if (exist == null || exist.equals("")) {
            return -3;
        }
        // // 审核不通过
        // if (!exist.getIsCheck().equals("1")) {
        //     return -1;
        // }
        //大于返回1，小于返回-1，等于返回0,报名时间不在范围内(签到时间小于活动开始时间)
        if ((new Date()).compareTo(sysEvent.getEventStart()) == -1) {
            return 0;
        }

        //不在签到时间内(活动结束前十分钟分钟不能签到)
        Long ms = DateUtils.getMs(new Date(), sysEvent.getEventEnd());
        if (ms > -600000) {
            return -2;
        }
        sysUserEvent.setStatusSignUp("1");
        sysUserEvent.setTimeSignUp(new Date());
        return sysUserEventMapper.updateSysUserEvent(sysUserEvent);
    }

    /**
     * 签退
     *
     * @return
     */
    @Override
    @Transactional
    public int SignOut(SysUserEvent sysUserEvent) {
        //查找是否存在报名信息
        SysUserEvent exist = sysUserEventMapper.selectOneSysUserEvent(sysUserEvent.getUserId(), sysUserEvent.getEventId());
        if (exist == null || exist.equals("")) {
            return -1;
        }

        int result = checkRole(exist.getUserId(),exist.getEventId());
        if(result != 0){
            return result;
        }

        // // 审核不通过
        // if (!exist.getIsCheck().equals("1")) {
        //     return -2;
        // }
        //未签到
        if (!exist.getStatusSignUp().equals("1")) {
            return -3;
        }
        //签退时间不在活动结束时间十分钟"前后"
        Date timeSignUp = exist.getTimeSignUp();
        Date timeSignOut = new Date();

        // 获取活动结束时间
        SysEvent sysEvent = sysEventMapper.selectSysEventByEventId(exist.getEventId());
        Long ms = DateUtils.getMs(timeSignOut, sysEvent.getEventEnd());
        if (Math.abs(ms) > 600000) {
            return 0;
        }

        String longtime = DateUtils.getDatePoor(timeSignOut, timeSignUp);

        // SysVolunteersTime sysVolunteersTime;
        // sysVolunteersTime = sysVolunteersTimeMapper.selectSysVolunteersTimeByUserId(sysUserEvent.getUserId());
        //
        // // 判断是否存在用户时长
        // if(sysVolunteersTime == null){
        //     sysVolunteersTime = new SysVolunteersTime();
        //     sysVolunteersTime.setUserId(sysUserEvent.getUserId());
        //     sysVolunteersTime.setTotalTime("0时0分");
        //     sysVolunteersTimeMapper.insertSysVolunteersTime(sysVolunteersTime);
        // }
        // Long TotalTimeMs = DateUtils.strToms(sysVolunteersTime.getTotalTime()) + DateUtils.strToms(longtime);
        // String TotalTime = DateUtils.msToStr(TotalTimeMs);
        // sysVolunteersTime.setTotalTime(TotalTime);
        //
        // //修改总服务时长失败
        // if (sysVolunteersTimeMapper.updateSysVolunteersTime(sysVolunteersTime) == 0) {
        //     return -4;
        // }

        sysUserEvent.setLongtime(longtime);
        sysUserEvent.setStatusSignOut("1");
        sysUserEvent.setTimeSignOut(timeSignOut);

        return sysUserEventMapper.updateSysUserEvent(sysUserEvent);
    }

    // 撤销活动报名
    @Override
    @Transactional
    public int removeUserEvent(Long user_id, Long event_id) {

        int result = checkRole(user_id,event_id);
        if(result != 0){
            return result;
        }
        // // 签退后不允许撤销报名
        SysUserEvent sysUserEvent = sysUserEventMapper.selectOneSysUserEvent(user_id, event_id);
        // if(sysUserEvent.getStatusSignOut().equals("1")){
        //     return -5;
        // }

        // 活动进行时不允许撤销报名
        SysEvent sysEvent = sysEventMapper.selectSysEventByEventId(event_id);
        String eventStatus = sysEvent.getEventStatus();
        if(eventStatus.equals("1")){
            return -5;
        }
        // 审核通过不允许撤销报名
        if(sysUserEvent.getIsCheck().equals("1")){
            return -4;
        }

        // 人数-1
        sysEventMapper.updatePeoples(event_id);
        return sysUserEventMapper.removeUserEvent(user_id, event_id);
    }

    // 审核
    @Override
    public int check(Long user_id, Long event_id) {

        int result = checkRole(user_id,event_id);
        if(result != 0){
            return result;
        }

        // 审核时间需在活动结束之后
        int num = checkTime(user_id, event_id);
        if(num != 0){
            return num;
        }

        // 审核成功用户总时长增加
        SysUserEvent sysUserEvent = sysUserEventMapper.selectOneSysUserEvent(user_id, event_id);

        SysVolunteersTime sysVolunteersTime;
        sysVolunteersTime = sysVolunteersTimeMapper.selectSysVolunteersTimeByUserId(user_id);

        // 判断是否存在用户时长
        if(sysVolunteersTime == null){
            sysVolunteersTime = new SysVolunteersTime();
            sysVolunteersTime.setUserId(user_id);
            sysVolunteersTime.setTotalTime("0时0分");
            sysVolunteersTimeMapper.insertSysVolunteersTime(sysVolunteersTime);
        }
        Long TotalTimeMs = DateUtils.strToms(sysVolunteersTime.getTotalTime()) + DateUtils.strToms(sysUserEvent.getLongtime());
        String TotalTime = DateUtils.msToStr(TotalTimeMs);
        sysVolunteersTime.setTotalTime(TotalTime);

        //修改总服务时长失败
        if (sysVolunteersTimeMapper.updateSysVolunteersTime(sysVolunteersTime) == 0) {
            return -4;
        }

        sysUserEvent.setIsCheck("1");
        return sysUserEventMapper.updateSysUserEvent(sysUserEvent);
    }

    // 审核失败
    @Override
    public int check_fail(Long user_id, Long event_id) {

        int result = checkRole(user_id,event_id);
        if(result != 0){
            return result;
        }

        // 审核时间需在活动结束之后
        int num = checkTime(user_id, event_id);
        if(num != 0){
            return num;
        }

        SysUserEvent sysUserEvent = new SysUserEvent();
        sysUserEvent.setUserId(user_id);
        sysUserEvent.setEventId(event_id);
        sysUserEvent.setIsCheck("2");
        return sysUserEventMapper.updateSysUserEvent(sysUserEvent);
    }


    /**
     * 自愿者只能处理自己的签到签退取消报名
     * 招募单位只能撤销自己的活动报名信息
     * @return
     */
    private int checkRole(Long userId,Long eventId) {
        LoginUser loginUser = SecurityUtils.getLoginUser();
        Long roleId = loginUser.getUser().getRoles().get(0).getRoleId();
        if(roleId == 2){
            if(!Objects.equals(userId, SecurityUtils.getUserId())){
                // 只能撤销自己的
                return -11;
            }
        }else if(roleId == 3){
            // 招募单位只能撤销自己的活动报名信息
            if(!Objects.equals(SecurityUtils.getUserId(), sysEventMapper.selectSysEventByEventId(eventId).getEventUserId())){
                return -12;
            }
        }
        return 0;
    }

    /**
     * 审核时间需在活动结束之后
     * @return
     */
    private int checkTime(Long userId,Long eventId){
        SysEvent sysEvent = sysEventMapper.selectSysEventByEventId(eventId);
        SysUserEvent sysUserEvent = sysUserEventMapper.selectOneSysUserEvent(userId, eventId);
        if(!sysUserEvent.getIsCheck().equals("0")){
            // 活动已审核
            return -14;
        }
        if(sysUserEvent.getStatusSignUp().equals("0") || sysUserEvent.getStatusSignOut().equals("0")){
            // 未签退
            return -15;
        }
        if(sysUserEvent.getImg() != null){
            // 请上传照片
            return -16;
        }
        if (DateUtils.getMs(sysEvent.getEventEnd(),new Date()) < 0){
            return 0;
        }
        return -13;
    }

}
